package com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ShowBigImageActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.adapter.SubjectImgAdapter;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.AnswerCallback;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.ScoreUtil;
import com.dayaokeji.rhythmschoolstudent.client.home.course.task.FilesAdapter;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.FilenameUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ImageUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.domain.ExamQuestion;
import com.dayaokeji.server_api.domain.SubjectAnswer;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import top.zibin.luban.Luban;

/**
 * 问答题
 */
public class QuestionAndAnswerFragment extends BaseSubjectFragment {

    private static final int CHOOSE_PIC_REQUEST_CODE = 1000;

    @BindView(R.id.tv_subject_type)
    TextView tvSubjectType;
    @BindView(R.id.tv_subject_score)
    TextView tvSubjectScore;
    @BindView(R.id.tv_subject_content)
    TextView tvSubjectContent;
    @BindView(R.id.rv_subject_imgs)
    RecyclerView rvSubjectImages;
    @BindView(R.id.rv_subject_answer_pic)
    RecyclerView rvSubjectAnswerPic;
    @BindView(R.id.et_question_and_answer)
    EditText etQuestionAndAnswer;

    private ExamQuestion examQuestion;
    private final SubjectImgAdapter subjectImgAdapter = new SubjectImgAdapter();
    private SubjectAnswer subjectAnswer = new SubjectAnswer();
    private FilesAdapter filesAdapter = new FilesAdapter();
    private final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private Call<ServerResponse<List<Integer>>> uploadCall;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    public static QuestionAndAnswerFragment newInstance(ExamQuestion examQuestion) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_EXAM_ENTITY,examQuestion);
        QuestionAndAnswerFragment fragment = new QuestionAndAnswerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_question_and_answer, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init() {
        examQuestion = (ExamQuestion) getArguments().getSerializable(EXTRA_EXAM_ENTITY);
        if (examQuestion == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }
        subjectAnswer.setExamQuestionId(examQuestion.getId());
        SubjectAnswer subjectAnswer = examQuestion.getSubjectAnswer();
        if (subjectAnswer != null) {
            examQuestion.setStudentAnswer(subjectAnswer.getAnswer());
        }
        if (!TextUtils.isEmpty(examQuestion.getStudentAnswer())) {
            this.subjectAnswer.setAnswer(examQuestion.getStudentAnswer());
            if (subjectAnswer != null) {
                examQuestion.getSubjectAnswer().setResourceList(subjectAnswer.getResourceList());
            }
        }

        setupView();
        setupViewData();
        if (!isExamResult()) {
            setOnListener();
        }else{
            navigationShowBigImage();
        }
    }

    private void setupView() {
        rvSubjectImages.setLayoutManager(new GridLayoutManager(getActivity(),4));
        rvSubjectImages.setAdapter(subjectImgAdapter);
        rvSubjectAnswerPic.setLayoutManager(new GridLayoutManager(getActivity(),4));
        rvSubjectAnswerPic.setAdapter(filesAdapter);
        setNavigationShowImage(subjectImgAdapter);
    }

    private void setupViewData() {
        tvSubjectType.setText(getSubjectTypeStr(examQuestion.getType()));
        tvSubjectScore.setText(String.format("分值：%s 分", ScoreUtil.doubleTrans(examQuestion.getScore())));
        tvSubjectContent.setText(examQuestion.getContent());
        subjectImgAdapter.setNewData(examQuestion.getResourceList());

        if (isExamResult()) {
            etQuestionAndAnswer.setEnabled(false);
            FilesAdapter.setIsShowDel(false);
        }else{
            FilesAdapter.setIsShowDel(true);
            initAddPicIcon();
        }
        if (!TextUtils.isEmpty(examQuestion.getStudentAnswer())) {
            etQuestionAndAnswer.setText(examQuestion.getStudentAnswer());
        }else{
            etQuestionAndAnswer.setHint("请输入答案");
        }

        if (isShowResult()) {
            String correctAnswer = examQuestion.getCorrectAnswer();
            if (TextUtils.isEmpty(correctAnswer)) {
                etQuestionAndAnswer.setHint("");
                etQuestionAndAnswer.setText(correctAnswer);
            }else{
                etQuestionAndAnswer.setText(correctAnswer);
            }
        }

        if (examQuestion.getAnswerResourceList() != null && !examQuestion.getAnswerResourceList().isEmpty()) {
            for (Integer resId : examQuestion.getAnswerResourceList()) {
                FilesAdapter.FileBean fileBean = new FilesAdapter.FileBean();
                fileBean.setRemoteImgResId(resId);
                if ((filesAdapter.getData().size()-1) < examQuestion.getAnswerResourceList().size()) {
                    filesAdapter.addData(0,fileBean);
                }
                subjectAnswer.getResourceList().add(resId);
            }
        }

        callbackResult();
    }

    private void initAddPicIcon() {
        if (filesAdapter.getData().size() < 1) {
            FilesAdapter.FileBean fileBean = new FilesAdapter.FileBean();
            fileBean.setFileRes(R.mipmap.ic_add_img);
            filesAdapter.addData(fileBean);
        }
    }

    private void navigationShowBigImage() {
        filesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FilesAdapter.FileBean fileBean = (FilesAdapter.FileBean) adapter.getData().get(position);
                if (fileBean.getRemoteImgResId() != -1) {
                    if (subjectAnswer.getResourceList().size() > position) {
                        ShowBigImageActivity.navigation(getActivity(),fileBean.getRemoteImgResId());
                    }
                }
            }
        });
    }

    private void setOnListener() {
        filesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FilesAdapter.FileBean fileBean = (FilesAdapter.FileBean) adapter.getData().get(position);
                if (TextUtils.isEmpty(fileBean.getFilePath()) && fileBean.getRemoteImgResId() == -1) {
                    if (AndPermission.hasPermissions(getActivity(), PermissionGroup.CAMERA_AND_STORE)) {
                        ImageUtil.captureImageByCamera(QuestionAndAnswerFragment.this,CHOOSE_PIC_REQUEST_CODE);
                    }else{
                        final PermissionUtil.Build build = new PermissionUtil.Build();
                        build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                        build.setTips("请允许我们访问拍照权限，以方便您进行拍问答");
                        compositeDisposable.add(PermissionUtil.checkPermission(getActivity(), build).subscribe(cameraConsumer));
                    }
                }else{
                    if (subjectAnswer.getResourceList().size() > position) {
                        ShowBigImageActivity.navigation(getActivity(),fileBean.getRemoteImgResId());
                    }
                }
            }
        });
        filesAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_del_img:
                        FilesAdapter.FileBean fileBean = (FilesAdapter.FileBean) adapter.getData().get(position);
                        delImgDialog(fileBean,position);
                        break;
                }
            }
        });

        etQuestionAndAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                subjectAnswer.setAnswer(s.toString());
                callbackResult();
            }
        });
    }

    private Consumer cameraConsumer = new Consumer<PermissionUtil.PermissionResult>() {
        @SuppressLint("CheckResult")
        @Override
        public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
            if (permissionResult.isHasAccess()) { // 允许拍照
                ImageUtil.captureImageByCamera(QuestionAndAnswerFragment.this,CHOOSE_PIC_REQUEST_CODE);
            }else{ // 未获取到拍照权限
                final PermissionUtil.Build build = new PermissionUtil.Build();
                build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                build.setTips("请允许我们访问拍照权限，以方便您进行拍照问答");
                compositeDisposable.add(PermissionUtil.checkPermission(getActivity(), build).subscribe(cameraConsumer));
            }
        }
    };

    private void callbackResult() {
        if (getActivity() != null) {
            if (getActivity() instanceof AnswerCallback) {
                ((AnswerCallback) getActivity()).callback(subjectAnswer);
            }
        }
    }

    private void delImgDialog(final FilesAdapter.FileBean fileBean,final int position) {
        DialogUtils.getAlertDialog(getActivity(), "提示", "确定删除当前图片？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!TextUtils.isEmpty(fileBean.getFilePath()) || fileBean.getRemoteImgResId() != -1) {
                    filesAdapter.getData().remove(fileBean);
                    filesAdapter.notifyDataSetChanged();
                    if (subjectAnswer.getResourceList().size() >= position) {
                        subjectAnswer.getResourceList().remove(position);
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_PIC_REQUEST_CODE) {
            final File captureImageFile = ImageUtil.getCaptureImageFile();
            compressionImageFile(captureImageFile.getPath());
        }
    }

    /**
     * 压缩文件
     *
     * @param filePath
     */
    @SuppressLint("CheckResult")
    private void compressionImageFile(final String filePath) {
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("提示");
        progressDialog.setMessage(FilenameUtils.getName(filePath)+"正在上传...");
        progressDialog.show();

        final Disposable disposable = Flowable.just(filePath).observeOn(Schedulers.io()).map(new Function<String, File>() {
            @Override
            public File apply(String s) throws Exception {
                if (TextUtils.isEmpty(s)) {
                    return null;
                }
                File file = new File(s);
                if (file.exists()) {
                    return Luban.with(getActivity()).load(s).get(s);
                }else{
                    return null;
                }
            }
        }).subscribe(new Consumer<File>() {
            @Override
            public void accept(File file) throws Exception {
                if (file != null) {
                    uploadFile(file,progressDialog);
                } else {
                    ToastUtils.warning("压缩文件失败");
                }
            }
        });
        compositeDisposable.add(disposable);
    }

    private void uploadFile(final File file,final ProgressDialog progressDialog) {
        RequestBody requestBody = RequestBody.create(MediaType.parse(FilenameUtils.getExtension(file.getPath())), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", file.getName(),requestBody);
        uploadCall = resourceApi.uploadTemp(filePart);

        uploadCall.enqueue(new ServerCallback<List<Integer>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                if (success) {
                    if (filesAdapter != null) {
                        final FilesAdapter.FileBean fileBean = new FilesAdapter.FileBean();
                        fileBean.setFilePath(file.getPath());
                        fileBean.setRemoteImgResId(response.getBody().get(0));
                        filesAdapter.addData(0,fileBean);
                    }
                    subjectAnswer.getResourceList().add(response.getBody().get(0));
                    callbackResult();
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    ToastUtils.success(FilenameUtils.getName(file.getPath()+"上传成功"));
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }
}
